package com.apache.websocket;

import com.apache.uct.common.ToolsUtil;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * description:工作流websocket
 * 定义一个org.springframework.web.socket.server.standard.ServerEndpointExporter的bean
 *
 * @author dyh 创建时间：2018年02月13日
 */
@ServerEndpoint("/userSocket")
public class UserWebsocketServer {

    private static CopyOnWriteArraySet<UserWebsocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    private Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        String sysPass = "sysPass=" + ToolsUtil.getInstance().getValueByKey("websocket_code_pass");
        String str = session.getQueryString();
        if (str.indexOf(sysPass) < 0) {
            session.close();
            return;
        }
        this.session = session;
        webSocketSet.add(this);
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        String sysPass = "sysPass=" + ToolsUtil.getInstance().getValueByKey("websocket_code_pass");
        String str = session.getQueryString();
        if (str.indexOf(sysPass) > -1) {
            // 群发消息
            sendToAll(str, message);
        }
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * Sends <var>text</var> to all currently connected WebSocket clients.
     */
    public void sendToAll(String resource, String text) throws IOException {
        String userEname = getUserEname(resource);
        synchronized (webSocketSet) {
            for (UserWebsocketServer c : webSocketSet) {
                if ("all".equalsIgnoreCase(userEname)) {
                    c.sendMessage(text);
                } else {
                    String ss = getUserEname(c.session.getQueryString());
                    if (userEname.indexOf(ss) > -1) {
                        c.sendMessage(text);
                    }
                }
            }
        }
    }

    protected String getUserEname(String resoruce) {
        String str[] = resoruce.split("&sysPass");
        if (str[0].indexOf("userEname") != -1) {
            String itemIds[] = str[0].split("=");
            return itemIds[1];
        }
        return "";
    }
}
